<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="depts"
        :props="props"
        :expand-on-click-node="false"
        icon-class="el-icon-office-building"
        default-expand-all
        highlight-current
      >
        <template #default="{data}">
          <el-row style="width: 100%" type="flex" justify="between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col align="center">{{ data.type }}</el-col>
            <el-col align="center">{{ data.managerName }}</el-col>
            <el-col align="center">{{ data.member || 0 }}人</el-col>
            <el-col align="center">
              <el-button type="text" @click="changeDepartment('edit',data.id)">编辑</el-button>
              <el-button type="text" style="margin: 0 10px" @click="del(data.id)">删除</el-button>
              <el-button type="text" @click="changeDepartment('add',data.id)">新增子项</el-button>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDept
    ref="addDept"
     :showDialog.sync="showDialog"
    :current-pid="currentPid"
    @updateDep="render"
    ></AddDept>
  </div>
</template>
<script>
import { delDepartment, getDepartmentList } from '@/api/department'
import AddDept from './components/add-dept.vue'
export default {
  name: 'ZuZhiJiaGou',
  components: {
    AddDept
  },
  props: {

  },
  data () {
    return {
      currentPid: 0,
      showDialog: false,
      depts: [],
      props: {
        label: 'name'
      }
    }
  },
  created () {
    this.render()
  },
  methods: {
    // 渲染
    async  render () {
      const res = await getDepartmentList()
      console.log(res)
      this.depts = this.listTOTreeList(res.data, 0)
    },
    // 删除部门
    async  del (id) {
      await this.$confirm('确认删除该部门吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
      await delDepartment(id)
      this.$message.success('删除成功')
      this.render()
    },
    // 编辑或者新增部门
    changeDepartment (type, id) {
      this.showDialog = true
      if (type === 'add') {
        this.currentPid = id
      } else if (type === 'edit') {
        this.currentPid = id
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      }
    },
    listTOTreeList (list, pid) {
      const arr = []
      list.forEach(item => {
        if (item.pid === pid) {
          item.children = this.listTOTreeList(list, item.id)
          arr.push(item)
        }
      })
      return arr
    }
  }
}
</script>
